package com.itzdm.user.controller;

import com.itzdm.client.domain.UserSearchDto;
import com.itzdm.common.result.Result;
import com.itzdm.common.constant.JwtClaimsConstant;
import com.itzdm.user.config.JwtConfig;
import com.itzdm.user.domain.dto.*;
import com.itzdm.user.domain.vo.UserChangeVo;
import com.itzdm.user.domain.vo.UserGetVo;
import com.itzdm.user.domain.vo.UserLoginVo;
import com.itzdm.user.domain.vo.UserRegisterVo;
import com.itzdm.user.service.IUserService;
import com.itzdm.user.utils.JwtUtil;
import com.itzdm.user.utils.MailMsg;
import com.itzdm.user.utils.MailUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @作者：张德明
 * @时间：2025/4/5 14:50
 */
@Api(tags = "用户相关接口")
@RestController
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final IUserService userService;
    private final JwtConfig jwtProperties;
    private final MailMsg mailMsg;

    /**
     * 用户登录
     * @param userLoginDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVo> login(@RequestBody @Validated UserLoginDto userLoginDto) {
        log.info("用户登录：{}", userLoginDto.toString());
        // 用户登录验证
        UserLoginVo login = userService.login(userLoginDto);
        // 登录成功后，生成 JWT 令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ID, login.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);
        login.setToken(token);
        // 返回登录成功的结果
        return Result.success(login);
    }


    /**
     * 用户注册
     * @param userRegisterDto
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result<UserRegisterVo> register(@RequestBody @Validated UserRegisterDto userRegisterDto) {
        log.info("用户注册：{}", userRegisterDto.toString());
        UserRegisterVo userRegisterVo = userService.register(userRegisterDto);
        return Result.success(userRegisterVo);
    }



    @PostMapping("/code")
    @ApiOperation("发送验证码")
    public Result<String> sendCode(@RequestBody UserCodeDto userCodeDto) {
        String email = userCodeDto.getEmail();
        log.info("发送验证码：{}", email);
        // 生成验证码
        if (!email.isEmpty()) {
            // 生成验证码
            String code = MailUtils.achieveCode();
//            String code = "1234";
            log.info("验证码为：{}", code);
            // 发送邮件
            try {
                mailMsg.mail(email, code);
            }  catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.success("发送成功");
    }

    /**
     * 修改密码
     * @param userPwdChangeDto
     * @return
     */
    @PutMapping("/password")
    @ApiOperation("修改密码")
    public Result<String> changePassword(@RequestBody UserPwdChangeDto userPwdChangeDto){
        log.info("修改密码：{}", userPwdChangeDto.toString());
        userService.changePassword(userPwdChangeDto);
        return Result.success("修改成功");
    }


    /**
     * 修改用户信息
     * @param userChangeDto
     * @return
     */
    @PutMapping("/profile")
    @ApiOperation("修改用户信息")
    public Result<UserChangeVo> changeUserInfo(@RequestBody UserChangeDto userChangeDto) {
        log.info("修改用户信息：{}", userChangeDto.toString());
        UserChangeVo userChangeVo = userService.changeUserInfo(userChangeDto);
        return Result.success(userChangeVo);
    }


    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    @ApiOperation("获取用户信息")
    public Result<UserGetVo> getUserInfo() {
        log.info("获取用户信息");
        UserGetVo userGetInfo = userService.getUserInfo();
        return Result.success(userGetInfo);
    }


    /**
     * 获取用户信息
     * @param keyword
     * @return
     */
    @GetMapping("/getUserInfoByKeyword")
    public UserSearchDto getUserInfo(@RequestParam("keyword") String keyword){
        return userService.getUserInfoByKeyword(keyword);
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfoById")
    public UserSearchDto getUserInfoById(@RequestParam("userId") Long userId){
        return userService.getUserInfoById(userId);
    }

    @GetMapping("/search/ids")
    public List<UserSearchDto> getUserInfoByIds(@RequestParam("userIds") List<Long> userIds) {
        return userIds.stream()
                .map(this::getUserInfoById)
                .filter(Objects::nonNull)
                .toList();
    }


    @PostMapping("/upload/avatar")
    @ApiOperation("用户上传头像")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        log.info("用户上传头像：{}", file.getOriginalFilename());
        // 上传头像
        String avatarUrl = userService.uploadAvatar(file);
        return Result.success(avatarUrl);
    }
}
